package com.seaking.controller;

import com.seaking.pojo.*;
import com.seaking.service.DataService;
import com.seaking.service.DepartmentService;
import com.seaking.service.SchoolService;
import com.seaking.service.TapService;
import com.seaking.util.CommonJson;
import com.seaking.util.CommonUtil;
import com.seaking.util.UUId;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.seaking.service.PlatformService;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.Id;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by wchha on 10/24 0024.
 */
@Controller
public class DataController {

    @Autowired
    private SchoolService schoolService;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private DataService dataService;

    @Autowired
    private TapService tapService;

    @Autowired
    private PlatformService platformService;

    @ResponseBody
    @RequestMapping(value = "/updateGood", method = RequestMethod.GET)
    public CommonJson updateGood(Integer id, HttpSession session) {
        if (id != null) {
            CommonJson json = new CommonJson();
            Integer good = (Integer) session.getAttribute(String.valueOf(id));
            if (good != null && good.equals(id)) {
                json.setSuccess(false);
                json.setMsg("请不要重复提交！");
                return json;
            }
            session.setAttribute(String.valueOf(id), id);
            dataService.updateGood(id);
            json.setMsg("点赞成功！");
            return json;
        }
        return null;
    }


    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public void download(Integer id, HttpServletResponse response, HttpServletRequest request) {
        response.setHeader("Content-Type", "application/octet-stream");
        Data data = null;
        if (id != null) {
            data = dataService.showDetail(id);
            try {
                response.setHeader("Content-Disposition", "attachment;filename = " + URLEncoder.encode(data.getResource(), "utf-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            String realPath = request.getServletContext().getRealPath("/");
            File file = new File(realPath + "static/zip/" + data.getResource());
            byte[] bytes = new byte[0];
            try {
                bytes = FileUtils.readFileToByteArray(file);
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                response.getOutputStream().write(bytes);
                dataService.updateClick(data);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }


    /**
     * 显示详细页面
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value = "/showDetail", method = RequestMethod.GET)
    public String showDetail(Model model, Integer id) {
        if (id != null && !id.equals("")) {
            Data data = dataService.showDetail(id);
            List<String> images = dataService.imageShow(data);
            model.addAttribute("images", images);
            model.addAttribute("data", data);
        }
        List<Data> datas = dataService.getTitle();
        model.addAttribute("datas", datas);
        return "show_detail";
    }


    @RequestMapping(value = "/addData", method = RequestMethod.GET)
    public String addData(Model model, HttpSession session) {
        List<School> schoolList = schoolService.getSchool();
        List<Department> department = departmentService.getDepartment();
        List<Tap> tap = tapService.getTap();
        List<Platform> platform = platformService.getPlatform();
        String token = UUId.random();
        session.setAttribute("token", token);
        model.addAttribute("schools", schoolList);
        model.addAttribute("departments", department);
        model.addAttribute("taps", tap);
        model.addAttribute("platforms", platform);
        model.addAttribute("token", token);
        return "add_data";
    }

    @RequestMapping(value = "/addData", method = RequestMethod.POST)
    public String addData(Model model, @RequestParam("file") MultipartFile[] photo, Data data, HttpSession session, String token) {
        String token1 = (String) session.getAttribute("token");
        if (token1 != null && token.equals(token1)) {
            session.removeAttribute("token");
        } else {
            model.addAttribute("msg", "请不要重复提交！");
            return "redirect:add_data";
        }
        if (data != null) {
            if (CommonUtil.isNullOrEmpty(data.getDepartment()) ||
                    CommonUtil.isNullOrEmpty(data.getPlatform()) ||
                    CommonUtil.isNullOrEmpty(data.getSchool()) ||
                    CommonUtil.isNullOrEmpty(data.getTitle()) ||
                    CommonUtil.isNullOrEmpty(data.getTap()) ||
                    CommonUtil.isNullOrEmpty(data.getDepartment())
                    ) {
                model.addAttribute("msg", "您的操纵有误！请重新登录");
                return "login";
            }
            if (photo.length > 3) {
                model.addAttribute("msg", "上传文件不允许超过三个");
                return "redirect:addData";
            }
            //数组验证数据
            Boolean aBoolean = checkFiles(photo);
            if (!aBoolean) {
                model.addAttribute("msg", "上传文件格式不正确，请重新发布！");
                return "redirect:addData";
            }
            try {
                dataService.saveFiles(photo, data);
                dataService.saveZip(photo, data);
                dataService.saveData(data);
            } catch (Exception e) {
                e.printStackTrace();
                model.addAttribute("msg", "上传失败，请重新上传！");
                return "redirect:addData";
            }
            model.addAttribute("msg", "上传成功！");
            return "redirect:index";
        }

        model.addAttribute("msg", "您的操纵有误！请重新登录");
        return "login";
    }


    private Boolean checkFiles(MultipartFile[] photo) {
        ArrayList<String> strings = new ArrayList<String>();
        strings.add(".jpg");
        strings.add(".png");
        strings.add(".gif");
        strings.add(".bmp");
        strings.add(".jpeg");
        for (MultipartFile file : photo) {
            String name = file.getOriginalFilename();
            boolean contains = strings.contains(name.substring(name.lastIndexOf(".")));
            if (!contains) return false;
        }
        return true;
    }
}
